package com.runvp.service.auth.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.runvp.common.core.redis.RedisCache;
import com.runvp.common.enums.*;
import com.runvp.common.exception.base.BaseException;
import com.runvp.common.model.auth.BizUserBO;
import com.runvp.common.model.auth.LoginUser;
import com.runvp.common.pay.alipay.AlipayClient;
import com.runvp.common.util.ToolUtils;
import com.runvp.common.utils.validtion.CheckException;
import com.runvp.service.biz.domain.BizCustomer;
import com.runvp.service.biz.service.IBizCustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AlipayAuthService {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IBizCustomerService bizCustomerService;


    public Map<String,Object> login(@PathVariable String authCode) throws Exception {
        Map<String,Object> loginInfo = new HashMap<>();
        log.info("alipay login request ,{}", authCode);
        AlipayClient client = new AlipayClient();
        // 1. 服务端获取access_token、user_id
        AlipaySystemOauthTokenResponse response = client.getAccessToken(authCode);
        log.info("alipay login response:{}",JSONObject.toJSONString(response));
        if (!response.isSuccess()) {
            throw new BaseException("登录失败,请联系管理员!");
        }
        String accessToken = response.getAccessToken();
        String alipayUserId = response.getUserId();
        // 如果用户不存在，则通过支付宝api获取用户的信息后，再注册用户到自己平台数据库
        AlipayUserInfoShareResponse aliUserInfo = client.getAliUserInfo(accessToken);
        log.info("aliUserInfo:{}",JSONObject.toJSONString(aliUserInfo));
        CheckException.strEmptyThrowException(alipayUserId,ErrorCode.AUTH_FAILURE.getDesc());
        BizCustomer customer = getBizCustomerByOpenId(alipayUserId);
        if(null == customer){
            //注册用户
            customer = new BizCustomer();
            customer.setOpenId(alipayUserId);
            customer.setSource(DataSource.ALIPAY.getCode());
            customer.setType(UserType.CUSTOMER.getCode());
            customer.setRealAuthStatus(YesOrNo.NO.getCode());
            customer.setPid(0L);
            customer.setStatus(EnableStatus.ENABLE.getCode());
            bizCustomerService.insertBizCustomer(customer);
        }
        if(!EnableStatus.ENABLE.getCode().equals(customer.getStatus())){
            throw new BaseException("您的账号存在风险，已做安全处理,请联系管理员!");
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(customer.getId());
        BizUserBO userBO = new BizUserBO();
        BeanUtils.copyProperties(customer,userBO);
        loginUser.setUserBO(userBO);
        Map<String,Object> map = tokenService.createToken(loginUser);
        loginInfo.put("aliUserInfo",aliUserInfo);
        loginInfo.put("token",ToolUtils.toStr(map.get("access_token")));
        return loginInfo;

    }


    private BizCustomer getBizCustomerByOpenId(String openId){
        BizCustomer query = new BizCustomer();
        query.setOpenId(openId);
        List<BizCustomer> customers = bizCustomerService.selectBizCustomerList(query);
        if(CollectionUtils.isEmpty(customers)){
            return null;
        }
        return customers.get(0);
    }

}
